package chatNI;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.InetAddress;
import java.net.Socket;

import javax.swing.JOptionPane;

/**
 * <b>Project ChatSystemG2 - INSA 4INFOA1 - 2013/2014</b>
 * <P>
 * <i>Package  chatNI</i> <br>
 * FileSender is the part of the chatNI that is related to the file sending. <br>
 * It extends Thread. 
 *
 * @author Sergio Gonzalez - Marie-Charlotte Bideaud
 */

public class FileSender extends Thread {

	final private int bufferSize = 1024;
	private InetAddress sourceAddress;
	private int port;
	private String path;
	private long fileSize;

	/**
	 * Method starting the thread
	 */
	public void run () {
		try {
			sendSocket();
			JOptionPane.showMessageDialog(null,
					"Succesfully sended.",
					"File send",JOptionPane.PLAIN_MESSAGE);
		} catch (IOException e) {
			JOptionPane.showMessageDialog(null,
					"An error occured during the file sending.",
					"File sending error",JOptionPane.ERROR_MESSAGE);
		}
	}

	/**
	 * Getter for sourceAddress
	 * 
	 * @return InetAddress
	 */
	public InetAddress getSourceAddress() {
		return sourceAddress;
	}

	/**
	 * Setter for sourceAddress
	 * 
	 * @param sourceAddress : InetAddress
	 */
	public void setSourceAddress(InetAddress sourceAddress) {
		this.sourceAddress = sourceAddress;
	}

	/**
	 * Getter for port
	 * 
	 * @return int
	 */
	public int getPort() {
		return port;
	}

	/**
	 * Setter for port
	 * 
	 * @param port : int
	 */
	public void setPort(int port) {
		this.port = port;
	}

	/**
	 * Getter for path
	 * 
	 * @return String
	 */
	public String getPath() {
		return path;
	}

	/**
	 * Setter for path 
	 * 
	 * @param path : String
	 */
	public void setPath(String path) {
		this.path = path;
	}

	/**
	 * Getter for fileSize
	 * 
	 * @return long
	 */
	public long getFileSize() {
		return fileSize;
	}

	/**
	 * Setter for fileSize
	 * 
	 * @param fileSize : long
	 */
	public void setFileSize(long fileSize) {
		this.fileSize = fileSize;
	}

	/**
	 * File sending method
	 * 
	 * @throws IOException
	 */
	public void sendSocket () throws IOException {
		// beginning of the sending
		Socket socket = new Socket(sourceAddress, port); 
		PrintStream ps = new PrintStream ( socket.getOutputStream() ); 
		FileInputStream source = new FileInputStream(path); 
		byte[] buffer = new byte[bufferSize]; 
		int len; 
		while ( (len = source.read(buffer) ) != -1 ) { 
			ps.write( buffer, 0, len); 
		}

		// end of the sending
		ps.close();
		source.close();
		socket.close();
	}
}
